#!/bin/bash

# 默认参数
SDK_PATH="/opt/OpenHarmony/Sdk/15"
ARCH="arm"

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --sdk-path)
            SDK_PATH="$2"
            shift 2
            ;;
        --arch)
            case $2 in
                arm|aarch64|x86_64)
                    ARCH="$2"
                    ;;
                *)
                    echo "Error: Invalid architecture. Must be one of: arm, aarch64, x86_64"
                    exit 1
                    ;;
            esac
            shift 2
            ;;
        *)
            echo "Unknown parameter: $1"
            exit 1
            ;;
    esac
done

# 设置OpenHarmony SDK路径
OH_SDK_HOME="${SDK_PATH}"
CLANG="${OH_SDK_HOME}/native/llvm/bin/clang++"
SYSROOT="${OH_SDK_HOME}/native/sysroot"
GCC_TOOLCHAIN="${OH_SDK_HOME}/native/llvm"

# 根据架构设置目标平台
case ${ARCH} in
    "arm")
        TARGET="arm-linux-ohos"
        ;;
    "aarch64")
        TARGET="aarch64-linux-ohos"
        ;;
    "x86_64")
        TARGET="x86_64-linux-ohos"
        ;;
esac

echo "Building for architecture: ${ARCH}"
echo "Using OpenHarmony SDK: ${OH_SDK_HOME}"

# 添加库路径
LIB_PATHS=(
    "-L${SYSROOT}/usr/lib"
    "-L${SYSROOT}/usr/lib/${TARGET}"
    "-L${OH_SDK_HOME}/native/share/libs"
    "-L${OH_SDK_HOME}/native/share/libs/multimedia"
)

# 编译参数
INCLUDES=(
    "-I${SYSROOT}/usr/include"
    "-I${OH_SDK_HOME}/native/share/include"
)
DEFINES="-DOHOS_PLATFORM"
FLAGS=(
    "--target=${TARGET}"
    "--gcc-toolchain=${GCC_TOOLCHAIN}"
    "--sysroot=${SYSROOT}"
    "-fPIC"
    "-Wall"
)

# 链接参数
LINK_FLAGS=(
    "${LIB_PATHS[@]}"
    "-lnative_avscreen_capture"
    "-lnative_buffer"
    "-lnative_media_core"
    "-lnative_media_avcencinfo"
    "-lnative_media_vdec"
    "-lnative_media_venc"
    "-lnative_media_codecbase"
    "-lhilog_ndk.z"
    "-lc++"
    "-lc"
    "-ldl"
)

# 检查库文件是否存在
echo "Checking library paths..."
for path in "${LIB_PATHS[@]}"; do
    lib_path=$(echo ${path} | sed 's/^-L//')
    if [ -d "${lib_path}" ]; then
        echo "Found library path: ${lib_path}"
        find "${lib_path}" -name "*multimedia*.so" -type f -exec echo "  Found library: {}" \;
    else
        echo "Warning: Library path not found: ${lib_path}"
    fi
done

# 编译源文件
echo "Compiling screenrecord.cpp..."
${CLANG} "${FLAGS[@]}" ${DEFINES} "${INCLUDES[@]}" -c screenrecord.cpp -o screenrecord.o

if [ $? -ne 0 ]; then
    echo "Error: Compilation failed!"
    exit 1
fi

# 链接可执行文件
echo "Linking executable..."
echo "Link command: ${CLANG} ${FLAGS[@]} screenrecord.o ${LINK_FLAGS[@]} -o screenrecord -v"
${CLANG} "${FLAGS[@]}" screenrecord.o "${LINK_FLAGS[@]}" -o screenrecord -v

if [ $? -ne 0 ]; then
    echo "Error: Linking failed!"
    exit 1
fi

echo "Build completed successfully!"